package gspushmq.v1.subscribe.send;

import java.util.Iterator;
import java.util.Set;

import org.java_websocket.WebSocket;

import gspushmq.model.ApiDataMessage;
import gspushmq.model.ApiMessage;
import gspushmq.model.ApiMessageType;
import gspushmq.util.GGLogger;
import gspushmq.v1.produce.GGDataStorage;
import gspushmq.v1.subscribe.GGSubscribe;
import gspushmq.v1.subscribe.send.core.GGSend;

/**
 *
 * 推送数据给前端
 * @version 1.0
 * @since JDK1.7
 * @author yutao
 * @company 上海朝阳永续信息技术有限公司
 * @copyright (c) 2016 SunTime Co'Ltd Inc.All rights reserved.
 * @date 2018年11月15日下午4:51:17
 */
public class GGSendApi extends GGSend {

	/**
	 * 发送api的数据
	 * @author yutao
	 * @date 2018年11月15日下午4:50:17
	 */
	public void handlerApi() {
		
		while(true){
			
			if(GGSubscribe.apiActiveQueue.isEmpty()){
				try {
					Thread.sleep(500);
					continue;
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			Iterator<ApiMessageType> iterator = GGSubscribe.apiActiveQueue.iterator();
//			synchronized (iterator) {
				while(iterator.hasNext()) {
					ApiMessageType apiMessType = iterator.next();
					
					Set<ApiMessage> apiMessSet = GGSubscribe.ApiUrlMessage.get(apiMessType);
					if(apiMessSet == null) {
						continue;
					}
					
					Iterator<ApiMessage> apiMessIt = apiMessSet.iterator();
					while(apiMessIt.hasNext()) {
						ApiMessage ams = apiMessIt.next();
						WebSocket wst = ams.getWst();
						ApiDataMessage apiDataMessage = GGDataStorage.ApiMessageMap.get(ams);
						if(wst.isOpen()) {
							if(apiDataMessage == null) {
								continue;
							}
							//发送消息给客户端
							sendWebSocket(ams, wst, apiDataMessage);
							GGDataStorage.ApiMessageMap.remove(ams);
						}else {
							GGLogger.warn(getClass(), "---websocket关闭---移除一个ApiMessage----" + ams.toString());
							apiMessIt.remove();
						}
					}
					GGSubscribe.apiActiveQueue.remove(apiMessType);
				}
//			}
		}
	}

	@Override
	public void handler() {
		handlerApi();
	}
}
